// background.js
"use strict";

import { app, protocol, BrowserWindow, ipcMain, dialog, desktopCapturer } from "electron";
import { createProtocol } from "vue-cli-plugin-electron-builder/lib";
import installExtension, { VUEJS3_DEVTOOLS } from "electron-devtools-installer";
const isDevelopment = process.env.NODE_ENV !== "production";
const path = require("path");
const { spawn } = require("child_process");
let ffmpegProcess;
let win;

const ffmpegPath = path.join(__dirname, 'ffmpeg', 'ffmpeg.exe');

protocol.registerSchemesAsPrivileged([
  { scheme: "app", privileges: { secure: true, standard: true } },
]);

async function createWindow() {
  win = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      preload: path.join(__dirname, "preload.js"),
      nodeIntegration: process.env.ELECTRON_NODE_INTEGRATION,
      contextIsolation: !process.env.ELECTRON_NODE_INTEGRATION,
    },
  });

  if (process.env.WEBPACK_DEV_SERVER_URL) {
    await win.loadURL(process.env.WEBPACK_DEV_SERVER_URL);
    if (!process.env.IS_TEST) win.webContents.openDevTools();
  } else {
    createProtocol("app");
    win.loadURL("app://./index.html");
  }
}

app.on("window-all-closed", () => {
  if (process.platform !== "darwin") {
    app.quit();
  }
});

app.on("activate", () => {
  if (BrowserWindow.getAllWindows().length === 0) createWindow();
});

app.on("ready", async () => {
  if (isDevelopment && !process.env.IS_TEST) {
    try {
      await installExtension(VUEJS3_DEVTOOLS);
    } catch (e) {
      console.error("Vue Devtools failed to install:", e.toString());
    }
  }
  createWindow();
});

// 获取窗口列表
ipcMain.on("get-windows", async (event) => {
  const sources = await desktopCapturer.getSources({ types: ['window'] });
  console.log(sources,'sources')
  event.reply("windows-list", sources);
});

function startRTMPStream(event, data) {
  const ffmpegCommand = ffmpegPath;
  const ffmpegArgs = [
    '-f', 'gdigrab',
    '-framerate', '60',
    '-i', `${data.input}`, // 使用窗口标题
    '-vcodec', 'libx264',
    '-preset', 'veryfast',
    '-f', 'flv',
    data.output
  ];

  if (ffmpegProcess) {
    stopRTSPStream();
  }

  ffmpegProcess = spawn(ffmpegCommand, ffmpegArgs);

  ffmpegProcess.stdout.on('data', (data) => {
    console.log(`FFmpeg stdout: ${data}`);
  });

  ffmpegProcess.stderr.on('data', (data) => {
    console.error(`FFmpeg stderr: ${data}`);
    event.reply("stream-error", { success: false, message: data.toString() });
  });

  ffmpegProcess.on('error', (error) => {
    console.error(`Error starting FFmpeg: ${error.message}`);
    event.reply("stream-error", { success: false, message: error.message });
  });

  ffmpegProcess.on('exit', (code) => {
    console.log(`FFmpeg exited with code: ${code}`);
    ffmpegProcess = null;
  });

  event.reply("stream-success", { success: true, message: "Stream started successfully." });
}

function stopRTSPStream() {
  if (ffmpegProcess) {
    console.log("Stopping RTSP stream...");
    ffmpegProcess.kill('SIGTERM');

    setTimeout(() => {
      if (ffmpegProcess) {
        console.log("FFmpeg did not exit, killing process forcefully.");
        ffmpegProcess.kill('SIGKILL');
      }
    }, 2000);

    console.log("RTSP stream stopped.");
  } else {
    console.log("No RTSP stream is currently running.");
  }
}

ipcMain.on("start-stream", (event, data) => {
  console.log("Starting RTMP stream with data:", data);
  startRTMPStream(event, data);
});

ipcMain.on("stop-stream", () => {
  console.log("Stopping RTSP stream");
  stopRTSPStream();
});
